import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { AppState } from "@store/index";

interface Credential {
  token: string;
  refresh_token: string;
}

const initialState: Credential = {
  token: "",
  refresh_token: "",
};

export const credentialSlice = createSlice({
  // 切片名称, 将会作为
  name: "credential",
  initialState,
  reducers: {
    // 保存用户登录凭据
    saveCredential(state, action: PayloadAction<Credential>) {
      state.token = action.payload.token;
      state.refresh_token = action.payload.refresh_token;
    },
    // 删除用户登录凭据
    clearCredential(state) {
      state.token = "";
      state.refresh_token = "";
    },
  },
});

// 获取 token
export const selectToken = (state: AppState) => state.credential.token;

export const { saveCredential, clearCredential } = credentialSlice.actions;
